/*
 * Copyright (C) 2009 CodeWerkz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.codewerkz.prompty;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.codewerkz.util.Utils;
import com.codewerkz.util.SettingsLoader.LoadSettings;


/**
 * Class for Creating/Editing a Presentation Activity.
 * 
 * @author ChaZ
 */
public class PresentationEdit extends Activity implements LoadSettings {

	// Set up globals.
	private EditText mTitleText;
    private EditText mBodyText;
    private CheckBox mPromptDelays;
    private Button mConfirmButton;
    private Long mRowId;
    private PresentationsDbAdapter mDbHelper;
    
    //private final String TAG = "Prompty - PrEdit";

    /**
     * Runs this function when the Activity is started.
     * 
     * @return void
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	// Create a new Database Adapter object and open the connection.
        mDbHelper = new PresentationsDbAdapter(this);
        mDbHelper.open();
        
        // Inflate the layout.
        setContentView(R.layout.presentation_edit);
        
        // Link up variables to relative layout object.
        mTitleText = (EditText) findViewById(R.id.presentationEdit_txtTitle);
        mBodyText = (EditText) findViewById(R.id.presentationEdit_txtBody);
        mConfirmButton = (Button) findViewById(R.id.presentationEdit_btnSave);
        mPromptDelays = (CheckBox) findViewById(R.id.presentationEdit_enableTimers);
       
        // Get the Row ID if the Activity unexpectedly closed or lost focus.
        mRowId = savedInstanceState != null ? savedInstanceState.getLong(PresentationsDbAdapter.KEY_ROWID) 
                							: null;
        
        // If there isn't a row id it means we can get it from the intent.
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();            
			mRowId = extras != null ? extras.getLong(PresentationsDbAdapter.KEY_ROWID) 
									: null;
		}
		
		// By this point, if the row id is null then the screen may have been turned.
		// Get the data from our future self.
		final Object data = getLastNonConfigurationInstance();
		// Check if the future self data isn't null.
		if ( data != null ) {
			// Set up us our row ID.
			this.mRowId = (Long) data;
		}

		// Populate the fields.
		populateFields();
		
		// Set up an onClick listener for the button.
        mConfirmButton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
        		// Set result and finish the activity.
        	    finish();
        	}
        });
        
        // Load the settings and set up the layout.
        loadSettings();
    }
    
	/**
	 * Loads the settings from the Main Activity and set's up any views with changes such as font. 
	 * 
	 * @param void
	 * @return void
	 */
    public void loadSettings() {  	  
    	// Set the font for the relevant views.
    	mBodyText.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	mConfirmButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	mPromptDelays.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	mTitleText.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	
    	TextView tmpTv = (TextView) this.findViewById(R.id.presentationEdit_lblTitle);
    	tmpTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	
    	tmpTv = (TextView) this.findViewById(R.id.presentationEdit_lblBody);
    	tmpTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, PresentationList.sFontSizePx);
    	
    	tmpTv = null;
    }
    
    /**
     * Runs when the Activity is paused (Loses focus etc.)
     * 
     * @return void
     */
    @Override
    protected void onPause() {
        super.onPause();
        // Save the state.
        saveState();
    }  
    
    /**
     * Runs when the Activity is resumed from the pause state.
     */
    @Override
    protected void onResume() {
        super.onResume();
        // Re-populate the fields.
        populateFields();
    }    
    
    /**
     * Runs when the Activity is about to be destroyed for Garbage Collection.
     * @return void
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	// Close the database adapter and set all references to views to null.
    	mDbHelper.close();
    	
    	mTitleText = null;
        mBodyText = null;
        mPromptDelays = null;
        mConfirmButton = null;
        mRowId = null;
    }
    
    /**
     * Runs when the instance is saved.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if ( mRowId != null ) {
        	outState.putLong(PresentationsDbAdapter.KEY_ROWID, mRowId);
        }
    }

    /**
     * Populates the on screen fields.
     * 
     * @return void
     */
    private void populateFields() {
    	// Check to see if there is a Row ID.
        if (mRowId != null && mRowId != 0) {
        	// Fetch the row from the database and set up the cursor.
            Cursor pres = mDbHelper.fetchPresentation(mRowId);            
            startManagingCursor(pres);
            
            // Set the fields to the values from the row.
            mTitleText.setText(pres.getString(
            		pres.getColumnIndexOrThrow(PresentationsDbAdapter.KEY_NAME)));
            mBodyText.setText(pres.getString(
            		pres.getColumnIndexOrThrow(PresentationsDbAdapter.KEY_DESC)));            
            mPromptDelays.setChecked(
            			Utils.intToBool(
		            		pres.getInt(
		                    		pres.getColumnIndexOrThrow(PresentationsDbAdapter.KEY_DELAYS))
            			));
        }
    }
    
    /**
     * Runs when our screen is rotated.
     * 
     * @return Object Contains a Long which has to be cast of the Row ID.
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
    	// Create and initialise row id.
    	long rowId = 0;
    	// If the member row id isn't null AND isn't 0...
    	if ( mRowId != null && mRowId != 0) {
    		// Set the variables.
    		rowId = mRowId;	
    	}
    	// return row id object.
    	return rowId;
    }
    
    /**
     * Saves the state. Helper function.
     */
    private void saveState() {
    	// Get the title and body from the layout.
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        boolean delays = mPromptDelays.isChecked();

        // If the Row Id is null, validate the fields and create a new Row.
        if (mRowId == null || mRowId == 0) {
        	if (title.length() != 0) {
	            long id = mDbHelper.createPresentation(title, body, delays);
	            if (id > 0) {
	                mRowId = id;
	            }
	            setResult(RESULT_OK);
        	} else {
        		// If the length IS ZERO, then set cancelled result so we can alert the user.
        		setResult(RESULT_CANCELED);
        	}
        // Otherwise update the existing presentation after validating the text.
        } else {
        	if (title.length() != 0) {
        		mDbHelper.updatePresentation(mRowId, title, body, delays);
        		setResult(RESULT_OK);
        	} else {
        		// If the length IS ZERO, then set cancelled result so we can alert the user.
        		setResult(RESULT_CANCELED);
        	}
        }
    }
    
}
